<script setup lang="ts">
import { onMounted, onUnmounted, ref, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { api, API_BASE_URL } from '@/utils/request'
import AppHeader from '@/components/layout/AppHeader.vue'
import { useGiftEffects } from '@/utils/useGiftEffects'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()

type ChatMessageItem = {
  id: string | number
  content: string
  messageType?: string
  imageUrl?: string
  username: string
  avatar: string
  timestamp: string | number | Date
  isSystem?: boolean
  isGift?: boolean
  senderUserId?: string
}
type ChatRoomDetail = { id: number; title?: string }
const room = ref<ChatRoomDetail | null>(null)
const loading = ref(false)
const messages = ref<ChatMessageItem[]>([])
let es: EventSource | null = null
const inputText = ref('')
const messagesContainer = ref<HTMLElement | null>(null)
const imageInput = ref<HTMLInputElement | null>(null)
const uploadingImage = ref(false)

// 初始化礼物特效
const giftEffects = useGiftEffects()

function scrollToBottom() {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

function pushMsg(m: ChatMessageItem) {
  messages.value.push(m)
  if (messages.value.length > 200) messages.value = messages.value.slice(-200)
  scrollToBottom()
}

async function fetchRoom() {
  loading.value = true
  try {
    const resp = await api.get(`/api/chat/rooms/${route.params.id}`)
    const data = await resp.json()
    room.value = JSON.parse(JSON.stringify(data))
  } catch (e) {
    console.error(e)
    router.replace('/home')
  } finally {
    loading.value = false
  }
}

// 移除历史消息加载功能 - 用户只能看到进入后的消息
// async function fetchHistory() {
//   try {
//     const resp = await api.get(`/api/chat/rooms/${route.params.id}/history?limit=50`)
//     const data = await resp.json()
//     for (const m of data.messages || []) {
//       messages.value.push(m)
//     }
//     if (messages.value.length > 200) messages.value = messages.value.slice(-200)
//     scrollToBottom()
//   } catch {}
// }

function connectSSE() {
  const sseUrl = `${API_BASE_URL}/api/chat/rooms/${route.params.id}/stream`
  console.log('用户端连接SSE:', sseUrl)

  es = new EventSource(sseUrl)

  es.addEventListener('open', () => {
    console.log('用户端SSE连接已建立')
  })

  es.addEventListener('error', (error) => {
    console.error('用户端SSE连接错误:', error)
  })

  es.addEventListener('message', (ev) => {
    console.log('用户端收到消息事件:', ev.data)
    pushMsg(JSON.parse(ev.data))
  })

  es.addEventListener('gift', (ev) => {
    console.log('用户端收到礼物事件:', ev.data)
    const data = JSON.parse(ev.data)
    pushMsg(data)
    // 触发特效（聊天室）
    try {
      const preset = data.giftEffectPreset || 'burst'
      console.log('触发礼物特效:', preset, '数量:', data.quantity)
      giftEffects.trigger(preset, Number(data.quantity || 1))
      console.log('礼物特效触发完成')
    } catch (error) {
      console.error('礼物特效触发失败:', error)
    }
  })

  es.addEventListener('system', (ev) => {
    console.log('用户端收到系统事件:', ev.data)
    pushMsg(JSON.parse(ev.data))
  })
}

async function sendMessage() {
  const text = inputText.value.trim()
  if (!text) return

  console.log('用户端发送消息:', text)
  try {
    const response = await api.post(`/api/chat/rooms/${route.params.id}/messages`, { content: text })
    console.log('用户端消息发送响应:', response)
    inputText.value = ''
    // 发送消息后滚动到底部
    scrollToBottom()
  } catch (error) {
    console.error('用户端发送消息失败:', error)
  }
}

// 选择图片
function selectImage() {
  imageInput.value?.click()
}

// 处理图片选择
async function handleImageSelect(event: Event) {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    alert('请选择图片文件')
    return
  }

  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    alert('图片文件不能超过10MB')
    return
  }

  uploadingImage.value = true
  try {
    // 上传图片
    const formData = new FormData()
    formData.append('image', file)

    const uploadResponse = await fetch(`${API_BASE_URL}/api/chat/rooms/${route.params.id}/upload-image`, {
      method: 'POST',
      credentials: 'include',
      body: formData
    })

    if (!uploadResponse.ok) {
      throw new Error('图片上传失败')
    }

    const uploadResult = await uploadResponse.json()
    console.log('图片上传成功:', uploadResult)

    // 发送图片消息
    const messageResponse = await api.post(`/api/chat/rooms/${route.params.id}/messages`, {
      messageType: 'image',
      imageUrl: uploadResult.imageUrl
    })

    console.log('图片消息发送成功:', messageResponse)
    scrollToBottom()
  } catch (error) {
    console.error('发送图片失败:', error)
    alert('发送图片失败，请重试')
  } finally {
    uploadingImage.value = false
    // 清空文件选择
    if (target) target.value = ''
  }
}

// 预览图片
function previewImage(imageUrl: string) {
  window.open(imageUrl, '_blank')
}

// 移除礼物相关代码，用户只能聊天

// 移除所有礼物相关函数

function formatTime(ts: string | number | Date) {
  const d = new Date(ts)
  return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

onMounted(async () => {
  if (!auth.user) await auth.fetchMe()
  if (!auth.user) {
    router.replace('/login')
    return
  }
  await fetchRoom()
  // 移除历史消息加载 - 用户只能看到进入后的消息
  // await fetchHistory()
  connectSSE()
})

onUnmounted(() => {
  if (es) {
    es.close()
    es = null
  }
})
</script>

<template>
  <div class="layout" v-if="auth.user">
    <AppHeader />
    <div class="chat-room" v-if="!loading && room">
      <div class="header">
        <button class="back" @click="router.back()">← 돌아가기</button>
        <h2>{{ room.title || '聊天室' }}</h2>
      </div>

      <div ref="messagesContainer" class="messages">
        <div
          v-for="m in messages"
          :key="m.id"
          class="msg"
          :class="{ mine: String(m.senderUserId) === String(auth.user?.id), sys: m.isSystem, gift: m.isGift }"
        >
          <img class="avatar" :src="m.avatar" alt="" />
          <div class="body">
            <div class="meta">
              <span class="name">{{ m.username }}</span>
              <span class="time">{{ formatTime(m.timestamp) }}</span>
            </div>
            <div class="bubble">
              <template v-if="m.messageType === 'image' && m.imageUrl">
                <img
                  :src="`${API_BASE_URL}${m.imageUrl}`"
                  :alt="m.content"
                  class="message-image"
                  @click="previewImage(`${API_BASE_URL}${m.imageUrl}`)"
                />
                <div class="image-caption">{{ m.content }}</div>
              </template>
              <template v-else>
                {{ m.content }}
              </template>
            </div>
          </div>
        </div>
      </div>

      <!-- 将工具栏放入同一文档流，顺序上在消息区域之后 -->
      <div class="toolbar">
        <input
          v-model="inputText"
          class="input"
          placeholder="메시지를 입력하세요"
          @keyup.enter="sendMessage"
        />
        <input
          ref="imageInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleImageSelect"
        />
        <button class="image-btn" @click="selectImage" title="이미지 전송">📷</button>
        <button class="send" @click="sendMessage">전송</button>
      </div>

      <!-- 移除礼物发送功能，用户只能聊天 -->
    </div>

    <div v-else-if="loading" class="loading">로딩 중...</div>
  </div>
</template>

<style scoped>
/* 整体布局 */
.layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
  color: var(--color-text);
  overflow: hidden;
}

/* 聊天室容器 */
.chat-room {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

/* 聊天室头部 */
.header {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-4);
  border-bottom: 1px solid var(--color-border);
  background: var(--color-bg);
  flex-shrink: 0;
  z-index: 30;
  box-shadow: var(--shadow-sm);
}

.header h2 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--color-text);
}

.back {
  background: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  padding: 8px 16px;
  border-radius: var(--radius-md);
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.back:hover {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

/* 消息区域（仅此处滚动） */
.messages {
  flex: 1;
  min-height: 0; /* 允许在flex容器中收缩以启用滚动 */
  overflow-y: auto;
  overflow-x: hidden;
  padding: var(--space-4);
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
  scroll-behavior: smooth;
  background: var(--color-surface-light);
}

/* 自定义滚动条 */
.messages::-webkit-scrollbar {
  width: 6px;
}

.messages::-webkit-scrollbar-track {
  background: var(--color-surface);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb {
  background: var(--color-border);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background: var(--color-text-muted);
}
/* 消息样式 */
.msg {
  display: flex;
  align-items: flex-start;
  gap: var(--space-2);
}

.msg.mine {
  flex-direction: row-reverse;
}

.msg .avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
  border: 2px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.msg .body {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.msg .meta {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: var(--space-2);
  color: var(--color-text-muted);
  font-size: 0.75rem;
  margin-bottom: 2px;
}

.msg .meta .name {
  font-weight: 600;
  color: var(--color-text);
}

.msg.mine .body {
  align-items: flex-end;
}

.msg.mine .meta {
  justify-content: flex-end;
  gap: 6px;
  text-align: right;
}

.msg.mine .meta .name {
  order: 2;
}

.msg.mine .meta .time {
  order: 1;
}

.msg .bubble {
  max-width: min(80%, 720px);
  width: fit-content;
  background: white;
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: 12px 16px;
  box-shadow: var(--shadow-sm);
  word-wrap: break-word;
  position: relative;
  line-height: 1.4;
}

.msg .bubble::before {
  content: '';
  position: absolute;
  top: 8px;
  left: -6px;
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-right: 6px solid white;
}

.msg.mine .bubble {
  margin-left: auto;
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
}

.msg.mine .bubble::before {
  left: auto;
  right: -6px;
  border-right: none;
  border-left: 6px solid var(--color-primary);
}

.msg.sys .bubble {
  background: var(--color-warning);
  color: var(--color-text);
  border-color: var(--color-warning);
  font-weight: 500;
  text-align: center;
  border-radius: var(--radius-full);
}

.msg.sys .bubble::before {
  display: none;
}

.msg.gift .bubble {
  background: linear-gradient(135deg, var(--color-accent), var(--color-accent-light));
  color: var(--color-text);
  border-color: var(--color-accent);
  font-weight: 600;
  box-shadow: var(--shadow-md);
}

.msg.gift .bubble::before {
  border-right-color: var(--color-accent);
}
/* 底部工具栏（作为页面内容的一部分） */
.toolbar {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-4);
  background: white;
  border-top: 1px solid var(--color-border);
  box-shadow: var(--shadow-lg);
  z-index: 20;
}

.input {
  flex: 1;
  padding: 12px 16px;
  background: var(--color-surface);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-full);
  color: var(--color-text);
  font-size: 14px;
  transition: all 0.2s;
}

.input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px color-mix(in oklab, var(--color-primary) 20%, transparent);
  background: white;
}

.input::placeholder {
  color: var(--color-text-muted);
}

.send {
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: var(--radius-full);
  padding: 12px 24px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.2s;
  box-shadow: var(--shadow-md);
}

.send:hover {
  background: color-mix(in oklab, var(--color-primary) 90%, black);
  transform: translateY(-1px);
  box-shadow: var(--shadow-lg);
}

.send:active {
  transform: translateY(0);
}

/* 图片按钮样式 */
.image-btn {
  background: var(--color-surface);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-full);
  padding: var(--space-3);
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
}

.image-btn:hover {
  background: var(--color-primary);
  color: white;
  border-color: var(--color-primary);
  transform: translateY(-1px);
}

/* 图片消息样式 */
.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all 0.2s;
  display: block;
  margin-bottom: var(--space-2);
}

.message-image:hover {
  transform: scale(1.02);
  box-shadow: var(--shadow-lg);
}

.image-caption {
  font-size: 12px;
  color: var(--color-text-muted);
  font-style: italic;
}

/* 移除礼物相关样式 */

/* 加载状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  font-size: 16px;
  color: var(--color-text-muted);
}
</style>
